package com.sms.api.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.sms.api.bean.ApiResult;
import com.sms.api.util.JSONUtils;
import com.sms.api.util.NewUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Random;

/**
 * 阿里云短信发送Service
 */
@Service
public class SmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsService.class);

    @Value("${sms.aliyun.secret}")
    private String secret;
    @Value("${sms.aliyun.key}")
    private String key;
    @Value("${sms.aliyun.templateCode}")
    private String templateCode;
    @Value("${sms.aliyun.signName}")
    private String signName;

    @Autowired
    private com.sms.api.service.SmsPolicyService SmsPolicyService;

    /**
     * 请求验证码
     * @param mobile
     * @return
     */
    public ApiResult<String> send(String mobile,HttpServletRequest httpServletRequest) {
        ApiResult<String> rest=new ApiResult<String>("0000","发送成功");
        //获取远程请求真实ip
        String ipAddr = NewUtils.getRealIp(httpServletRequest);
        logger.info("进入短信发送策略请求IP:{}",ipAddr);
        //=========短信策略,0000代码策略通过================//
        ApiResult policy = SmsPolicyService.policy(mobile, httpServletRequest);
        //创建验证码
        String verification_code = String.valueOf(new Random().nextInt(899999) + 100000);//生成短信验证码
        //如果通过策略则走发短信流程
        if("0000".equals(policy.getError_code())) {
            //阿里云发送短信代码
            DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", secret, key);
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest CommonRequest = new CommonRequest();
            CommonRequest.setSysMethod(MethodType.POST);
            CommonRequest.setSysDomain("dysmsapi.aliyuncs.com");
            CommonRequest.setSysVersion("2017-05-25");
            CommonRequest.setSysAction("SendSms");
            CommonRequest.putQueryParameter("RegionId", "cn-hangzhou");
            CommonRequest.putQueryParameter("PhoneNumbers",mobile);
            CommonRequest.putQueryParameter("TemplateCode",templateCode);
            CommonRequest.putQueryParameter("SignName",signName);
            CommonRequest.putQueryParameter("TemplateParam","{\"code\":\""+verification_code+"\"}");
            try {
                CommonResponse response = client.getCommonResponse(CommonRequest);
                Map<String, Object> map = JSONUtils.toHashMap(response.getData());
                if("OK".equals(map.get("Code"))){
                    rest.setError_code("0000");
                    rest.setData(map.get("Message").toString()+"；请求ip:"+ipAddr);
                }else{
                    rest.setError_code("0009");
                    rest.setMessage("短信通道发送失败,原因:"+map.get("Message").toString()+"；请求ip:"+ipAddr);  //发送失败返回失败详细原因
                    rest.setData(map.get("Message").toString());
                }
                logger.info("短信发送SDK返回信息："+response.getData());
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }

        if(!"0000".equals(policy.getError_code())){
            logger.info("【未通过短信策略】"+policy.getMessage());
            rest = new ApiResult<String>(policy.getError_code(),policy.getMessage());
            rest.setData(policy.getMessage());
            return rest;
        }else {
            return rest;
        }
    }



//    public Object verification(PlayerVerificationRequest pammermap) {
//        com.shijie.box.db.dto.ApiResult rest = new com.shijie.box.db.dto.ApiResult();
//        String phone = pammermap.getPhone();
//        if (StringUtil.isEmpty(phone)) {
//            rest.setError_code("0001");
//            rest.setMessage("手机号为空");
//        }
//        BaseUserExample exam = new BaseUserExample();
//        exam.or().andUsernameEqualTo(phone).andDeletestatusEqualTo(false);
//        BaseUser user = userMapper.selectOneByExample(exam);
//        if (user == null) {
//            rest.setError_code("0002");
//            rest.setMessage("手机号不正确");
//        }
//        String code = pammermap.getCode();
//        // 判断验证码
//        if (null == code || "".equals(code)) {
//            rest.setError_code("0003");
//            rest.setMessage("code不能为空！");
//            return rest;
//        }
//
//        if ("666666".equals(code) && "dev".equals(current_environment)) { // 开发阶段不用总是调用短信登录接口
//        } else {
//            BaseSmsExample smsexample = new BaseSmsExample();
//            smsexample.or().andMobileEqualTo(phone).andVerificationCodeEqualTo(code).andCheckCodeEqualTo("0");
//            smsexample.setOrderByClause("add_time   desc");
//            List<BaseSms> list = smsMapper.selectByExample(smsexample);
//            if (StringUtil.isEmpty(list)) {
//                rest.setError_code(CodesEnum.FAIL0009.getCode());
//                rest.setMessage("验证码错误");
//                return rest;
//            }
//            for (int i = 0; i < list.size(); i++) {
//                BaseSms baseSms = list.get(i);
//                LocalDateTime addtime = baseSms.getAddTime();
//                LocalDateTime now = LocalDateTime.now();
//                Duration duration = Duration.between(now, addtime);
//                long minutes = Math.abs(duration.toMinutes());
//                baseSms.setCheckCode("1");
//                if (minutes > deadline) {
//                    baseSms.setCheckCode("2");
//                    rest.setError_code(CodesEnum.FAIL0010.getCode());
//                    rest.setMessage("验证码已失效");
//                    smsMapper.updateByPrimaryKey(baseSms);
//                    return rest;
//                }
//                baseSms.setExpirationTime(now);
//                smsMapper.updateByPrimaryKey(baseSms);
//            }
//        }
//        rest.setError_code("0000");
//        rest.setMessage("请求成功");
//        return rest;
//    }
//
//    public ApiResult<String> check(SmsFangweiCheckResquest resquest) {
//        ApiResult<String> rest =new ApiResult<String>("0000","校验成功");
//        String mobile=resquest.getMobile();
//        String verification_code=resquest.getCode();
//        String sendForm=resquest.getSendFrom();
//
//        BaseSmsExample example=new BaseSmsExample();
//        example.or().andMobileEqualTo(mobile).andVerificationCodeEqualTo(verification_code).andCheckCodeEqualTo("0");
//        example.setOrderByClause("add_time   desc");
//        List<BaseSms> list=dao.selectByExample(example);
//        if(StringUtil.isEmpty(list)) {
//            rest.setError_code(CodesEnum.FAIL0009.getCode());
//            rest.setMessage("验证码错误");
//            return rest;
//        }
//        for (int i = 0; i < list.size(); i++) {
//            BaseSms baseSms=list.get(i);
//            LocalDateTime addtime=baseSms.getAddTime();
//            LocalDateTime now=LocalDateTime.now();
//            Duration duration=Duration.between(now, addtime);
//            long minutes=Math.abs(duration.toMinutes());
//            baseSms.setCheckCode("1");
//            if(minutes>deadline) {
//                baseSms.setCheckCode("2");
//                rest.setError_code(CodesEnum.FAIL0010.getCode());
//                rest.setMessage("验证码已失效");
//            }
//            baseSms.setExpirationTime(now);
//            dao.updateByPrimaryKey(baseSms);
//        }
//
//
//        return rest;
//    }


}
